// utils/util.js
/**
 * 时间戳转日期格式
 */
function formatTime(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * 数字格式化，个位数前补0
 */
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 计算购物车商品总数
 */
function getCartTotalCount() {
  const cartList = wx.getStorageSync('cartList') || []
  let totalCount = 0
  cartList.forEach(item => {
    totalCount += item.count
  })
  return totalCount
}

/**
 * 更新购物车数量显示
 */
function updateCartBadge() {
  const count = getCartTotalCount()
  if (count > 0) {
    wx.setTabBarBadge({
      index: 2,
      text: count.toString()
    })
  } else {
    wx.removeTabBarBadge({
      index: 2
    })
  }
}

/**
 * 加入购物车
 */
function addToCart(goods) {
  const cartList = wx.getStorageSync('cartList') || []
  const index = cartList.findIndex(item => item.id === goods.id)
  
  if (index > -1) {
    // 已存在，增加数量
    cartList[index].count += 1
  } else {
    // 新增商品
    cartList.push({
      id: goods.id,
      name: goods.name,
      price: goods.price,
      originalPrice: goods.originalPrice,
      image: goods.image,
      count: 1,
      selected: true, // 默认选中
      stock: goods.stock // 库存
    })
  }
  
  wx.setStorageSync('cartList', cartList)
  updateCartBadge()
  
  return cartList
}

/**
 * 从购物车移除商品
 */
function removeFromCart(goodsId) {
  let cartList = wx.getStorageSync('cartList') || []
  cartList = cartList.filter(item => item.id !== goodsId)
  wx.setStorageSync('cartList', cartList)
  updateCartBadge()
  return cartList
}

/**
 * 获取购物车列表
 */
function getCartList() {
  return wx.getStorageSync('cartList') || []
}

/**
 * 计算购物车选中商品总价
 */
function getCartTotalPrice() {
  const cartList = getCartList()
  let total = 0
  cartList.forEach(item => {
    if (item.selected) {
      total += item.price * item.count
    }
  })
  return total.toFixed(2)
}

/**
 * 计算购物车选中商品总数
 */
function getCartSelectedCount() {
  const cartList = getCartList()
  let count = 0
  cartList.forEach(item => {
    if (item.selected) {
      count += item.count
    }
  })
  return count
}

/**
 * 获取选中的商品
 */
function getSelectedGoods() {
  const cartList = getCartList()
  return cartList.filter(item => item.selected)
}

/**
 * 检查登录状态
 */
function checkLogin() {
  return wx.getStorageSync('token') && wx.getStorageSync('userInfo')
}

/**
 * 跳转到登录页
 */
function goLogin() {
  wx.showModal({
    title: '提示',
    content: '请先登录',
    success: (res) => {
      if (res.confirm) {
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }
    }
  })
}

module.exports = {
  formatTime,
  getCartTotalCount,
  updateCartBadge,
  addToCart,
  removeFromCart,
  getCartList,
  getCartTotalPrice,
  getCartSelectedCount,
  getSelectedGoods,
  checkLogin,
  goLogin
}    